package com.heo.queue.task;

import java.net.InetSocketAddress;
import java.text.DateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

import com.heo.pojo.DeviceReceivePacketHistoryEntity;
import com.heo.pub.ApplicationContextUtil;
import com.heo.pub.ServerConfig;
import com.heo.queue.TaskQueue;
import com.heo.server.SocketChannelMap;
import com.heo.service.DeviceReceivePacketHistoryService;
import com.heo.util.ByteHelper;

import io.netty.channel.Channel;

/**
 * 处理接收到的消息线程
 * 接收消息线程负责将收到的消息写入数据库。应答的内容由应答线程进行处理。
 */

public class ReceiveTaskThread implements Runnable
{
  private static Logger log = Logger.getLogger(SendTaskThread.class);
  private static String THREAD_NAME = "[接收指令线程]";
  private static final int SLEEP_TIME = 100;//每次休息100毫秒

  public ReceiveTaskThread()
  {

  }

  @Override
  public void run()
  {
    try
    {
      sendTask();
    }
    catch (Exception e)
    {
      log.error(e.getMessage(), e);
      log.error(THREAD_NAME + "线程出现严重异常，已退出运行。");
    }
  }

  public void sendTask() throws Exception
  {
    log.debug(THREAD_NAME + "线程开始执行。");
    while (TaskQueue.getReceiveTaskSize() > 0)
    {
      ReceiveTask receiveTask = TaskQueue.pollReceiveTask();// 不阻塞
      if (receiveTask == null)
      {
        continue;
      }
      String channelId = null;
      String remoteIpAddress = null;
      String logHeader = null;
      try
      {
        Channel channel = SocketChannelMap.getSocketChannelByIMEI(receiveTask.getDeviceInfoEntity().getDeviceImei());
        if (channel != null)
        {
          channelId = channel.id().asShortText();
          remoteIpAddress = ((InetSocketAddress) channel.remoteAddress()).getAddress().getHostAddress();
          logHeader = "[server][" + channelId + "][" + remoteIpAddress + "]";
        }
        else
        {
          log.info(logHeader + THREAD_NAME + "处理接收设备的消息时，设备已不在线。");
        }

        // 更新时间状态
        ServerConfig.LAST_RECEIVE_TIME = DateFormat.getDateTimeInstance().format(new Date());

//        // 进行业务处理
//        DeviceReceivePacketHistoryService service = (DeviceReceivePacketHistoryService) ApplicationContextUtil.getBeanById("deviceReceivePacketHistoryService");
//        DeviceReceivePacketHistoryEntity drphe = new DeviceReceivePacketHistoryEntity();
//        drphe.setChannelId(channelId);
//        drphe.setCommandId(ByteHelper.shortToHexString((short) receiveTask.getBasePacket().getCommandId()));
//        drphe.setCommandName(receiveTask.getBasePacket().getPacketName());
//        drphe.setDeviceIemi(receiveTask.getDeviceInfoEntity().getDeviceImei());
//        drphe.setPacketContent(ByteHelper.byteToHexString(receiveTask.getBasePacket().getPacketBody()));
//        drphe.setPacketData(receiveTask.getBasePacket().toString());
//        drphe.setPacketLength(receiveTask.getBasePacket().getTotalLength());
//        drphe.setReceiveTime(receiveTask.getBasePacket().getCreateTime());
//        drphe.setExecuteTime(new Date());
//        drphe.setSequenceId(ByteHelper.shortToHexString((short) receiveTask.getBasePacket().getSequenceId()));
//        drphe.setServerId(ServerConfig.SERVIER_ID);
//        service.insert(drphe);
        Thread.sleep(SLEEP_TIME);
      }
      catch (Exception e)
      {
        // 处理失败，重新进队列
        boolean result = TaskQueue.offerReceiveTask(receiveTask,false);
        log.error(logHeader + THREAD_NAME + "处理接收数据异常，重新放入队列发送。进队列结果：" + result);
        log.error(e.getMessage(), e);
      }
    }
    log.debug(THREAD_NAME + "线程执行完毕。");
  }

}
